<?php

namespace App\Admin\Forms;

use App\Jobs\GenerateAgreementJob;
use App\Jobs\JobQueue;
use App\Models\User;
use App\Notifications\ToPayNotify;
use Dcat\Admin\Admin;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\Log;

class ToPayForm extends Form
{
    use LazyWidget;
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {

        $row = $this->payload['row'] ?? null;
        $user = $row['user'];

        // 最后一条审核记录
        $lastLog = $row['audit_log'] ? json_decode($row['audit_log'], true) : [];

        // 劳务审核状态
        if ($input['pay_status'] == '2') {
            $audit_fee = '1';
            \App\Models\ProjectExportRecord::where('id', $row['records_id'])
                ->increment('pay_success');
        } elseif ($input['pay_status'] == '-1') {
            $audit_fee = '-1';
            \App\Models\ProjectExportRecord::where('id', $row['records_id'])
                ->increment('pay_fail');
        }
        // 当前审核记录
        $log = [
            [
                'audit_global_status' => $row['audit_global_status'],
                'audit_user' => Admin::user()->name,
                'audit_time' => date('Y-m-d H:i:s'),
                'pay_status' => $input['pay_status'],
                'audit_remark' => $input['audit_remark'] ?? '',
                'audit_fee' => $audit_fee,
            ],
        ];

        try {

            \App\Models\ProjectAgreement::where('id', $row['project_agreement_id'])
                ->update(array_merge([
                    'audit_fee' => $audit_fee, // 劳务审核
                    'status' => $audit_fee,
                    'audit_remark' => ($audit_fee == 1 ? '' : $input['audit_remark']),
                    'audit_log' => \json_encode(array_merge($lastLog, $log), 256),
                    'pay_status' => $input['pay_status'],
                    'receipt_form' => $input['receipt_form'] ? $input['receipt_form'] : '',
                    'paymentd_at' =>  $input['paymentd_at'] ? $input['paymentd_at'] : null,
                ]));


            \App\Models\ProjectExportRecordsDetail::where('id', $row['id'])
                ->update(array_merge([
                    'audit_fee' => $audit_fee, // 劳务审核
                    'status' => $audit_fee,
                    'audit_remark' => ($audit_fee == 1 ? '' : $input['audit_remark']),
                    'audit_log' => \json_encode(array_merge($lastLog, $log), 256),
                    'pay_status' => $input['pay_status'],
                    'receipt_form' => $input['receipt_form'] ? $input['receipt_form'] : '',
                    'paymentd_at' =>  $input['paymentd_at'] ? $input['paymentd_at'] : null,
                ]));

            // todo 找产品要具体的通知规则
            if (1) {
                Log::info('------ 发送通知 ToPay ------');
                $user = User::where('id', $row['user']['id'])->first();

                \Illuminate\Support\Facades\Notification::send(
                    $user,
                    (new ToPayNotify($input, $user))->onQueue(JobQueue::PAY_NOTIFY)
                );
            }
            return $this
                ->response()
                ->success('操作成功')
                ->refresh();
        } catch (\Exception $e) {
            Log::info('----------catch----------', ['exception' => json_encode($e)]);
            return $this
                ->response()
                ->error('操作失败')
                ->refresh();
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->select('pay_status', '审核状态')->options(['2' => '审核通过', '-1' => '审核驳回'])->when(
            '-1',
            function (Form $form) {
                $form->textarea('audit_remark', '审核意见');
            }
        )->when(
            '2',
            function (Form $form) {
                $form->multipleImage('receipt_form', '上传回执单')
                    ->accept('jpg,png,gif,jpeg')
                    ->help('只允许上传jpg、png、gif、jpeg格式的图片文件')
                    ->saveFullUrl()
                    ->autoUpload()

                    ->rules('required_if:status,1', ['required_if' => '请填写完整该项'])
                    ->saving(function ($value) {
                        return implode(',', httpToHttps($value));
                    });
                $form->datetime('paymentd_at', '支付时间');
            }
        )->required();
    }

    // 返回表单数据，如不需要可以删除此方法
    public function
    default()
    {
        // 获取外部传递参数
        $id = $this->payload['id'] ?? null;
        return [
            'pay_status'   => $this->payload['row']['pay_status'],
            'receipt_form' => $this->payload['row']['receipt_form'],
            'paymentd_at'  => $this->payload['row']['paymentd_at']
        ];
    }
}
